//
//  ZBDUnit.m
//  ZDB
//

//

#import "ZBDUnit.h"
#import "sys/utsname.h"
#import "AppDelegate.h"
#import "ZDBBindWXViewController.h"
@implementation ZBDUnit
+ (UIWindow *)KWindow;
{
    UIWindow* window = nil;
    
    window = [UIApplication sharedApplication].keyWindow;
    
    return window;
 
}
/*
 iphoneX
 */
+ (BOOL)deviceIsIPhoneX {
    struct utsname systemInfo;
    
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    if ([platform isEqualToString:@"i386"] || [platform isEqualToString:@"x86_64"]) {
        // 模拟器下采用屏幕的高度来判断
        return [UIScreen mainScreen].bounds.size.height == 812;
    }
    // iPhone10,6是美版iPhoneX 感谢hegelsu指出：https://github.com/banchichen/TZImagePickerController/issues/635
    BOOL isIPhoneX = [platform isEqualToString:@"iPhone10,3"] || [platform isEqualToString:@"iPhone10,6"];
    return isIPhoneX;
}

+ (void)showMessage:(NSString *)message
{
    static BOOL isShow = NO;
    if (isShow) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        isShow = YES;
        CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];
        style.messageFont = AutoFont(14);
        style.verticalPadding =10;
        style.cornerRadius = 4;
        style.messageColor = WHITECOLOR;
        style.backgroundColor = BLACKCOLOR;
       
        
        [kWindow makeToast:message
                  duration:2
                  position:CSToastPositionCenter
                     style:style];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            isShow = NO;
        });
    });
}
// 颜色转换三：iOS中十六进制的颜色（以#开头）转换为UIColor
+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // 判断前缀并剪切掉
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
//*   *//
/**
 查找指定字符串的富文本
 
 @param str str
 @param attributedArray 字符串数组
 @param colors color
 @param font font
 @return 富文本
 */
+ (NSMutableAttributedString *)finderattributedString:(NSString *)str
                                      attributedArray:(NSArray *)attributedArray
                                               colors:(NSArray *)colors
                                                 font:(UIFont*)font;
{
    NSMutableAttributedString *muattributeString = [[NSMutableAttributedString alloc] initWithString:str];
    for (int i =0; i<attributedArray.count; i++) {
        NSString * attributedString = attributedArray[i];
        NSRange range1 = [[muattributeString string] rangeOfString:attributedString];
        [muattributeString addAttribute:NSForegroundColorAttributeName value:colors[i] range:range1];
    }
   
    NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:4];
    [muattributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [str length])];
    return muattributeString;
}
+ (NSMutableAttributedString *)finderattributedString:(NSString *)str attributedString:(NSString *)attributedString color:(UIColor *)color font:(UIFont *)font
{
    
    NSRange range = [str rangeOfString:attributedString];
    NSMutableAttributedString *muattributeString  = [[NSMutableAttributedString alloc]initWithString:str];
    [muattributeString addAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:font} range:range];
    
    
    return muattributeString;
}
+ (NSMutableAttributedString *)finderattributedLinesString:(NSString *)str attributedString:(NSString *)attributedString color:(UIColor *)color font:(UIFont *)font
{
    
    NSRange range = [str rangeOfString:attributedString];
    NSMutableAttributedString *muattributeString  = [[NSMutableAttributedString alloc]initWithString:str];
    NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:6];
    [muattributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [str length])];
    [muattributeString addAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:font} range:range];
    
    
    return muattributeString;
}

+ (NSMutableAttributedString *)getcontent:(NSString *)str image:(NSString *)imageStr index:(NSInteger)index imageframe:(CGRect)imageframe
{
    CGFloat y = imageframe.origin.y;
    if (y == 0) {
        y = RealValue_H(1);
    }
    NSMutableAttributedString *attri       = [[NSMutableAttributedString alloc] initWithString:str];
    NSTextAttachment *attch                = [[NSTextAttachment alloc] init];
    attch.image                            = [UIImage imageNamed:imageStr];
    attch.bounds                           = CGRectMake(0,y, imageframe.size.width,imageframe.size.height);
    
    NSAttributedString *string             = [NSAttributedString attributedStringWithAttachment:attch];
    [attri insertAttributedString:string atIndex:index];
    return attri;
}
//获取Window当前显示的ViewController
+ (UIViewController*)currentViewController{
//    AppDelegate *appdele = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    UIViewController *vc  =  appdele.window.rootViewController;
    
        UIWindow* window = [UIApplication sharedApplication].keyWindow;
        UIViewController* vc = (UIViewController *)window.rootViewController;
    
    if ([vc isKindOfClass:[UITabBarController class]]) {
        vc = ((UITabBarController*)vc).selectedViewController;
    }
    
    if ([vc isKindOfClass:[UINavigationController class]]) {
        vc = ((UINavigationController*)vc).visibleViewController;
    }
    
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    }
    
    return vc;
}
/* 获取登陆权限*/
+ (BOOL)getTaskJurisdiction;
{
    if (![DJLoginHelper sharedInstance].is_Login) {
        [[DJLoginHelper sharedInstance] dj_showLoginVC:[self currentViewController]];
        return NO;
    }
    if (![DJLoginHelper sharedInstance].is_BindWX) {
        if ([DJLoginHelper sharedInstance].wx_Status.integerValue ==1) { //1=审核中 2=审核失败 3=审核通过
//             [JMNotifyView showNotify:@"审核资质正在审核中,请等待审核" isSuccessful:NO];
            return YES;
        }else if ([DJLoginHelper sharedInstance].wx_Status.integerValue ==2 )
        {
//            __block ZDBCustomerAlearView * custom = [[ZDBCustomerAlearView alloc] initWithtititle:@"温馨提示" content:@"你资料审核失败\n请重新上传软件相关截图完成资料审核" cancel:@"稍后处理" submit:@"重新提交"];
//            [custom showLXAlertView];
//            WeakSelf
//            [custom.submitBtn add_BtnClickHandler:^(NSInteger tag) {
//                [custom dismissAlertView];
//                ZDBBindWXViewController *bindWXVC = [[ZDBBindWXViewController alloc] init];
//                [[weakSelf currentViewController].navigationController pushViewController:bindWXVC animated:YES];
//
//            }];
            return YES;
            
        }else if ([DJLoginHelper sharedInstance].wx_Status.integerValue ==3)
        {
            return YES;
        }
        
        __block ZDBCustomerAlearView * custom = [[ZDBCustomerAlearView alloc] initWithtititle:@"温馨提示" content:@"你还未通过资料审核\n请上传软件相关截图完成资料审核" cancel:@"稍后处理" submit:@"提交资料"];
        [custom showLXAlertView];
        WeakSelf
        [custom.submitBtn add_BtnClickHandler:^(NSInteger tag) {
            [custom dismissAlertView];
            ZDBBindWXViewController *bindWXVC = [[ZDBBindWXViewController alloc] init];
            [[weakSelf currentViewController].navigationController pushViewController:bindWXVC animated:YES];
            
        }];
        return NO;
    }
    return YES;
}
/* 获取登陆权限*/
+ (BOOL)getLoginJurisdiction;
{
    if (![DJLoginHelper sharedInstance].is_Login) {
        [[DJLoginHelper sharedInstance] dj_showLoginVC:[self currentViewController]];
        return NO;
    }
    return YES;
}
//获取应用当前版本号
+ (NSString *)getVersion
{
    //此获取的版本号对应bundle，打印出来对应为12345这样的数字
    //    NSNumber *number = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
    
    //此获取的版本号对应version，打印出来对应为1.2.3.4.5这样的字符串
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
+ (BOOL)JudgeTheillegalCharacter:(NSString *)content{
    //提示 标签不能输入特殊字符
    NSString *str =  @"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    //@"^[A-Za-z0-9\\u4e00-\u9fa5]+$”;
    NSPredicate * emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}
/**
  字符串转时间戳 如：2017-4-10 17:15:10
  
  @param time 时间
  @return 时间戳
  */
+ (NSString *)getOtherTimeStrWithString:(NSString *)formatTime{
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];

    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    NSDate* data=[self nsstringConversionNSDate:formatTime];
    NSString* string=[dateFormat stringFromDate:data];
    return string;
    
}

+(NSDate *)nsstringConversionNSDate:(NSString *)dateStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datestr = [dateFormatter dateFromString:dateStr];
    return datestr;
}
@end
